<template>
  <div :class="$style.wrap">
    <ContentWrap>
      <FormContainer :column="4">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
          <el-form-item label="待办类型" prop="taskType">
            <el-select v-model="formData.taskType" placeholder="请选择待办类型" clearable filterable>
              <el-option v-for="(bt,i) in backLogType" :key="i" :value="bt.dictCode" :label="bt.dictName"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="待办状态" prop="state">
            <el-select v-model="formData.state" placeholder="请选择待办状态" clearable filterable>
              <el-option v-for="(bs,i) in backLogStatus" :key="i" :value="bs.value" :label="bs.label"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="时间" prop="operateTime">
            <el-date-picker v-model="formData.operateTime" opt type="daterange" start-placeholder="开始时间" end-placeholder="结束时间" clearable></el-date-picker>
          </el-form-item>
          <el-form-item>
            <Button type="primary" enter @click="clickHandle">查询</Button>
            <Button type="primary" @click="batHandle">批量处理</Button>
          </el-form-item>
        </el-form>
      </FormContainer>
      <table-box ref="table" no-request :other-filters="otherFilters" :table-config="tableConfig" @selection-change="selectionChange">
        <el-table-column slot="before" type="selection" align="center" width="50" :selectable="selectableHandle" />
      </table-box>
    </ContentWrap>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import FormContainer from '@/components/FormContainer'
import { ccDict } from '@/api/dataDict'
import { putWaitHandleTask, putBatWaitHandleTask, getWorkOrderState } from '@/api/waitHandle'
import { filtersRaw, date24 } from '@/utils'
import { mapGetters, mapActions } from 'vuex'
export default {
  name: 'BackLogDetail',
  components: {
    ContentWrap,
    FormContainer
  },
  data() {
    return {
      otherFilters: [], // 查询参数
      backLogType: [], // 待办类型
      backLogStatus: [
        {
          value: 0,
          label: '待处理'
        },
        {
          value: 1,
          label: '已处理'
        }
      ], // 待办状态
      formData: {
        taskType: '',
        state: 0,
        operateTime: []
      },
      formRules: {

      },
      selectedList: [],
      tableConfig: {
        interfacePath: '/call-center/api/v1/waitHandleTask/page',
        pageFlag: true,
        hideFuncBar: true,
        sort: 'operateTime',
        order: 'desc',
        // 表格字段动态配置
        setting: [
          {
            prop: 'taskType',
            label: '待办类型',
            propEnum: {
              appCode: 'call-center',
              domainCode: 'marketing',
              dictTypeCode: 'BACKLOG_TASK_TYPE' // FIXME:
            }
          },
          {
            prop: 'businessCode',
            label: '业务编号',
            width: 180
          },
          {
            prop: 'sourceSystem',
            label: '系统'
          },
          {
            prop: 'operator',
            label: '操作人'
            // formatData: v => `${v.operator}(${v.handler})`
          },
          {
            prop: 'operateContent',
            label: '操作内容'
          },
          {
            prop: 'operateTime',
            label: '操作时间',
            width: 150
          },
          {
            prop: 'state',
            label: '待办状态',
            formatData: v => {
              if (v.state === 0) {
                return '待处理'
              } else {
                return '已处理'
              }
            }
          },
          {
            label: '操作',
            align: 'center',
            width: 150,
            render: (_, row) => {
              const show = row.state === 0
              // return (
              //   <div>
              //     <Button type='primary' onClick={this.preview.bind(this, row)}>查看</Button>
              //     <Button type='primary' onClick={this.operator.bind(this, row)} style={{ display: show ? 'block' : 'none' }}>处理</Button>
              //   </div>
              // )
              const t = []
              t.push(_('Button', {
                attrs: {
                  type: 'primary'
                },
                on: {
                  click: () => {
                    this.preview(row)
                  }
                }
              }, '查看'))
              if (show) {
                t.push(_('Button', {
                  attrs: {
                    type: 'primary'
                  },
                  on: {
                    click: () => {
                      this.operator(row)
                    }
                  }
                }, '处理'))
              }
              return _('div', {
                style: {
                  textAlign: 'left'
                }
              }, t)
            }
          }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['accountNo'])
  },
  created() {
    this.getTaskTypeDict()
    // 从首页跳转过来时，默认加载未处理
    if (this.$route.query.from === 'index') {
      this.clickHandle()
    }
  },
  methods: {
    ...mapActions(['getWaitCount']),
    clickHandle() {
      if (!this.accountNo) {
        return
      }
      const t = []
      t.push(filtersRaw('handler', this.accountNo, '='))
      if (this.formData.taskType !== '') {
        t.push(filtersRaw('taskType', this.formData.taskType, '='))
      }
      if (this.formData.state !== '') {
        t.push(filtersRaw('state', this.formData.state, '='))
      }
      if (this.formData.operateTime && this.formData.operateTime.length === 2) {
        t.push(filtersRaw('operateTime', this.formData.operateTime[0], '>'))
        t.push(filtersRaw('operateTime', date24(this.formData.operateTime[1]), '<='))
      }
      this.otherFilters = t
      this.refresh()
    },
    // 处理
    async  operator(row) {
      // this.$msgbox({
      //   title: '提示',
      //   message: '确认处理该工单吗？',
      //   showCancelButton: true,
      //   type: 'warning'
      // }).then(() => {
      //   putWaitHandleTask({
      //     id: row.id,
      //     state: 1
      //   }).then(res => {
      //     this.$message.success('处理成功！')
      //     this.refresh()
      //     this.getWaitCount()
      //     this.$router.push({ name: 'DisposeOrderDetails', query: { id: row.businessId }})
      //   })
      // })
      const workOrderState = await this.getWorkOrderState(row.businessId) // 工单状态:0保存1接收2处理中3完结

      putWaitHandleTask({
        id: row.id,
        state: 1
      }).then(res => {
        this.$message.success('处理成功！')
        this.refresh('onPage')
        this.getWaitCount()
        // this.$router.push({ name: 'DisposeOrderDetails', query: { id: row.businessId }})
        // 工单状态为0时 跳到创建页面
        if (workOrderState === 0) this.$router.push({ name: 'CreateOrder', query: { id: row.businessId, state: 0, type: 'edit' }})
        else this.$router.push({ name: 'DisposeOrderDetails', query: { id: row.businessId }})
      })
    },
    // 查看
    preview(row) {
      if (!row.businessCode) {
        this.$message.warning('数据异常')
        return
      }
      this.$router.push({ name: 'QueryOrderDetails', query: { workOrderNo: row.businessCode, form: 'telRecord' }})
    },
    // 获取任务类型字典
    getTaskTypeDict() {
      ccDict('BACKLOG_TASK_TYPE').then(res => {
        this.backLogType = res.data
      })
    },
    // 刷新
    refresh(onPage) {
      this.$nextTick(() => {
        this.$refs.table.initTableData(onPage)
      })
    },
    selectionChange(v) {
      this.selectedList = v
    },
    // 是否可选
    selectableHandle(row, index) {
      return row.state !== 1 && row.state !== '1'
    },
    // 批量处理
    batHandle() {
      if (this.selectedList.length <= 0) {
        this.$message.info('请选择要处理的待办！')
        return
      }
      return this.$msgbox({
        title: '提示',
        message: '确定批量处理待办？',
        showCancelButton: true,
        type: 'warning'
      }).then(() => {
        const ids = this.selectedList.map(e => e.id)
        return putBatWaitHandleTask(ids).then(res => {
          this.$message.success('处理成功！')
          this.refresh('onPage')
        })
      })
    },
    async  getWorkOrderState(id) {
      const { success, data } = await getWorkOrderState(id)

      if (success === 1 && data) {
        return data.workOrderState
      }
    }
  }
}
</script>
<style lang='scss' module>
.wrap{
    [class*="table-button-box"]{
        [class*="el-button"]{
            padding: 0 !important;
        }
    }
    tr{
      background-color: white !important;
    }
}
</style>
